package cn.pegasus.teamwork.pegasus.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.aliyuncs.exceptions.ClientException;

import cn.iyizhan.teamwork.base.service.impl.BaseServiceImpl;
import cn.iyizhan.teamwork.base.util.PageObject;
import cn.pegasus.teamwork.pegasus.entity.BussGeneralAccount;
import cn.pegasus.teamwork.pegasus.entity.BussServiceProject;
import cn.pegasus.teamwork.pegasus.entity.BussUserConsumorder;
import cn.pegasus.teamwork.pegasus.entity.BussUserFunddetails;
import cn.pegasus.teamwork.pegasus.entity.BussUserFundstatistics;
import cn.pegasus.teamwork.pegasus.entity.BussUserInfo;
import cn.pegasus.teamwork.pegasus.entity.BussUserOrder;
import cn.pegasus.teamwork.pegasus.entity.BussUserReward;
import cn.pegasus.teamwork.pegasus.entity.BussWasherFunddetails;
import cn.pegasus.teamwork.pegasus.entity.BussWasherFundstatistics;
import cn.pegasus.teamwork.pegasus.entity.BussWasherInfo;
import cn.pegasus.teamwork.pegasus.entity.BussWasherSgin;
import cn.pegasus.teamwork.pegasus.mapper.BussGeneralAccountMapper;
import cn.pegasus.teamwork.pegasus.mapper.BussServiceProjectMapper;
import cn.pegasus.teamwork.pegasus.mapper.BussUserConsumorderMapper;
import cn.pegasus.teamwork.pegasus.mapper.BussUserFunddetailsMapper;
import cn.pegasus.teamwork.pegasus.mapper.BussUserFundstatisticsMapper;
import cn.pegasus.teamwork.pegasus.mapper.BussUserInfoMapper;
import cn.pegasus.teamwork.pegasus.mapper.BussUserOrderMapper;
import cn.pegasus.teamwork.pegasus.mapper.BussUserRewardMapper;
import cn.pegasus.teamwork.pegasus.mapper.BussWasherFunddetailsMapper;
import cn.pegasus.teamwork.pegasus.mapper.BussWasherFundstatisticsMapper;
import cn.pegasus.teamwork.pegasus.mapper.BussWasherInfoMapper;
import cn.pegasus.teamwork.pegasus.mapper.BussWasherSginMapper;
import cn.pegasus.teamwork.pegasus.service.BussServiceProjectService;
import cn.pegasus.teamwork.pegasus.service.BussUcenterAreaService;
import cn.pegasus.teamwork.pegasus.service.BussUserConsumorderService;
import cn.pegasus.teamwork.pegasus.service.BussUserOrderService;
import cn.pegasus.teamwork.pegasus.service.BussUserRewardService;
import cn.pegasus.teamwork.pegasus.service.BussWasherInfoService;
import cn.pegasus.teamwork.sysconfig.entity.SysConfigDictionary;
import cn.pegasus.teamwork.sysconfig.mapper.SysConfigDictionaryMapper;
import cn.pegasus.teamwork.sysconfig.service.SysConfigMessageService;
import cn.pegasus.teamwork.util.DateCompareUtil;
import cn.pegasus.teamwork.util.PasswordEncoder;
import cn.pegasus.teamwork.util.SmsUtils;
import cn.pegasus.teamwork.util.SnowflakeIdWorker;
import cn.pegasus.teamwork.vo.WXOrderVO;
import cn.pegasus.teamwork.weixinpay.Constant;
import cn.pegasus.teamwork.weixinpay.service.PayService;

/**
 * @author ryan.bian
 * @version
 */
@Service("bussUserOrderService")
public class BussUserOrderServiceImpl extends BaseServiceImpl<BussUserOrder, BussUserOrderMapper>
		implements BussUserOrderService {

	private static final Logger LOGGER = LoggerFactory.getLogger(BussUserOrderServiceImpl.class);

	// 注入当前dao对象
	@Autowired
	private BussUserOrderMapper bussUserOrderMapper;

	@Autowired
	private BussWasherInfoMapper washerInfoMapper;

	@Autowired
	private BussUserInfoMapper userInfoMapper;

	@Autowired
	private BussServiceProjectMapper serviceProjectMapper;

	@Autowired
	private BussWasherFunddetailsMapper washerFunddetailsMapper;

	@Autowired
	private BussWasherFundstatisticsMapper washerFundstatisticsMapper;

	@Autowired
	private BussUserFunddetailsMapper userFunddetailsMapper;

	@Autowired
	private BussUserFundstatisticsMapper userFundstatisticsMapper;
	@Autowired
	private BussServiceProjectService serviceProjectService;
	@Autowired
	private SysConfigDictionaryMapper sysConfigDictionaryMapper;
	@Autowired
	private BussWasherInfoService washerInfoService;
	@Autowired
	private BussUserRewardService userRewardService;
	@Autowired
	private PayService payService;
	/**
	 * 用户消费订单表service
	 */
	@Autowired
	private BussUserConsumorderService consumorderService;

	@Autowired
	private SysConfigMessageService messageService;

	@Autowired
	private BussWasherFunddetailsMapper bussWasherFunddetailsMapper;
	@Autowired
	private BussUserRewardMapper bussUserRewardMapper;
	@Autowired
	private BussGeneralAccountMapper generalAccountMapper;

	@Autowired
	private BussWasherSginMapper washerSginMapper;
	@Autowired
	private BussUserConsumorderMapper bussUserConsumorderMapper;

	public BussUserOrderServiceImpl() {
		setMapperClass(BussUserOrderMapper.class, BussUserOrder.class);
	}

	@Autowired
	private BussUcenterAreaService ucenterAreaService;

	/**
	 * 对于用户下的洗车订单，进行洗车工的分配 分配原则，先匹配小区信息，然后匹配
	 */
	// public int createDispatchOrder(BussUserOrder bus) {
	// // 1. 先根据订单中的定位查找附近洗车工列表
	// int area_id = bus.getAreaId();
	// BussUcenterArea area = new BussUcenterArea();
	// area.setId(Long.valueOf(area_id));
	// area = ucenterAreaMapper.selectSingle(area);
	// if (area != null) {
	// BussWasherInfo w = new BussWasherInfo();
	// w.setAreaId(Integer.valueOf(area.getId().toString()));
	// List<BussWasherInfo> ws = washerInfoMapper.selectByObject(w);
	// List<Integer> resultMap = getWasherIds(ws,
	// DateCompareUtil.getDateToString(bus.getBespokeBeginTime()));
	// int wid = getBeginSerWasherId(resultMap);
	// if (wid != 0) {
	// bus.setWasherId(wid);
	// bus.setOrderIsassign(1);
	// bussUserOrderMapper.updateByEntity(bus);
	//
	// return wid;
	// } else {
	// int sid = getBeginSenSerWasherId(resultMap, bus.getBespokeBeginTime(),
	// bus.getBespokeEndTime());
	// if (sid != 0) {
	// bus.setWasherId(sid);
	// bus.setOrderIsassign(1);
	// bussUserOrderMapper.updateByEntity(bus);
	//
	// return sid;
	// }
	// }
	// }
	//
	// else {
	// LOGGER.debug("没有找到相应想小区信息");
	// return 0;
	// }
	//
	// return 0;
	// }

	/**
	 * 分配洗车工ID
	 */
	public int createDispatchOrder(BussUserOrder bus) {

		String reservationDate = DateCompareUtil.getDateToDateString(bus.getBespokeBeginTime());

		int areaId = bus.getAreaId();
		Date beginDate = DateCompareUtil.getNowDate(reservationDate + " 9:00:00");
		Date endDate = DateCompareUtil.getNowDate(reservationDate + " 21:00:00");

		// 获取小区存正的洗车工，都是已经签到的洗车工
		// 对于用户 打卡进行筛选
		List<BussWasherSgin> bwi = getBussWasherInfos(areaId, reservationDate);
		if (bwi != null && bwi.size() > 0) {
			String sure = DateCompareUtil.getDayForHours(bus.getBespokeBeginTime(), bus.getBespokeEndTime());
			for (BussWasherSgin bs : bwi) {
				// 上午签到
				String sgin_morning = bs.getSginMorning();
				// 下午签到
				String sgin_afternoon = bs.getSginAfternoon();
				if (!StringUtils.isEmpty(sgin_morning)) {
					if (DateCompareUtil.isInTime(sgin_morning, sure)) {
						// 验证员工订单
						Map<String, Object> tmap = new HashMap<String, Object>();
						tmap.put("areaId", areaId);
						int washerId = bs.getWasherId();
						tmap.put("washerId", washerId);
						tmap.put("beginDate", beginDate);
						tmap.put("endDate", endDate);
						List<BussUserOrder> vos = bussUserOrderMapper.findOrderInfoBySpoke(tmap);
						if (vos != null && vos.size() > 0) {
							int count = 0;
							for (BussUserOrder bo : vos) {
								String rs = DateCompareUtil.getDayForHours(bo.getBespokeBeginTime(),
										bo.getBespokeEndTime());
								if (!StringUtils.isEmpty(rs)) {
									if (!DateCompareUtil.isInTime(sure, rs)) {
										count = count + 1;
									}
								}
							}

							if (count == vos.size()) {
								return washerId;
							}
						} else {
							return washerId;
						}
					}
				}

				if (!StringUtils.isEmpty(sgin_afternoon)) {
					if (DateCompareUtil.isInTime(sgin_afternoon, sure)) {
						// 验证员工订单
						Map<String, Object> tmap = new HashMap<String, Object>();
						tmap.put("areaId", areaId);
						int washerId = bs.getWasherId();
						tmap.put("washerId", washerId);
						tmap.put("beginDate", beginDate);
						tmap.put("endDate", endDate);
						List<BussUserOrder> vos = bussUserOrderMapper.findOrderInfoBySpoke(tmap);
						if (vos != null && vos.size() > 0) {
							int count = 0;
							for (BussUserOrder bo : vos) {
								String rs = DateCompareUtil.getDayForHours(bo.getBespokeBeginTime(),
										bo.getBespokeEndTime());
								if (!StringUtils.isEmpty(rs)) {
									if (!DateCompareUtil.isInTime(sure, rs)) {
										count = count + 1;
									}
								}
							}
							if (count == vos.size()) {
								return washerId;
							}
						} else {
							return washerId;
						}
					}
				}
			}
		} else {
			return 0;
		}

		return 0;
	}

	/**
	 * 查询洗车工是否都已经开始了服务
	 * 
	 * @param ws
	 * @return
	 */
	public int getBeginSerWasherId(List<Integer> resultMap) {
		if (resultMap != null && resultMap.size() > 0) {
			for (int i = 0; i < resultMap.size(); i++) {
				if (getwasherId(resultMap.get(i), 1)) {
					if (getwasherId(resultMap.get(i), 2)) {
						return resultMap.get(i);
					}
				}
			}
		}
		return 0;
	}

	/**
	 * 查询洗车工是否都已经开始了服务
	 * 
	 * @param ws
	 * @return
	 */
	public boolean getwasherId(int washerId, int type) {
		if (washerId > 0) {
			// 查询该洗车工的已经开始订单
			BussUserOrder or = new BussUserOrder();
			or.setWasherId(washerId);
			or.setOrderStatus(type);
			List<BussUserOrder> odr = bussUserOrderMapper.selectByObject(or);
			// 该洗车工已经开始洗车
			if (odr != null && odr.size() > 0) {
				return false;
			} else {
				return true;
			}
		}
		return false;
	}

	/**
	 * 参数组装
	 * 
	 * @param ws
	 * @return
	 */
	public List<Integer> getWasherIds(List<BussWasherInfo> ws, String beginDate) {
		List<Integer> resultMap = new ArrayList<Integer>();
		if (ws != null) {
			for (BussWasherInfo w : ws) {
				// 判断洗车工是否已经打卡、查询洗车是否已经签到
				BussWasherSgin wss = new BussWasherSgin();
				Date da = DateCompareUtil.getDateToString(beginDate.substring(0, 10));
				wss.setWasherId(w.getId());
				wss.setSginDate(DateCompareUtil.getDateToDateString(da));
				wss = washerSginMapper.selectSingle(wss);
				if (wss != null && wss.getId() != null) {
					resultMap.add(w.getId());
				}
			}
			return resultMap;
		}

		return resultMap;
	}

	@Override
	public void handleRefundsOrderMoney(BussUserOrder bo) {
		// 2. 创建洗车工明细表
		createWasherFunddetails(bo, 1);

		// 3. TODO 此处暂时不做结算任务 修改用户资金总表信息
		// updateWasherFundstatisticsReduce(bo);

		// 4. 创建用户明细表
		createUserFunddetails(bo, 3);

		// 5. 修改用户资金总表信息
		updateUserFundstatisticsAdd(bo, 2);
	}

	/**
	 * 洗车工资金明细信息
	 * 
	 * @param map
	 * @return
	 */
	public void createWasherFunddetails(BussUserOrder bo, int type) {
		try {
			BussWasherFunddetails bcf = new BussWasherFunddetails();
			bcf.setWasherId(Integer.valueOf(bo.getWasherId().toString()));
			bcf.setOrderId(bo.getId());

			// 资金明细类型（1-洗车收入；2-打赏收入；10-提现支出；12-退款支出；）
			if (type == 1) {
				bcf.setCapitalType(1);
			} else if (type == 2) {
				bcf.setCapitalType(2);
			} else if (type == 10) {
				bcf.setCapitalType(10);
			} else if (type == 11) {
				bcf.setCapitalType(11);
			}

			// 交易时间
			bcf.setTransactionTime(DateCompareUtil.getNowDate());

			// 交易金额
			bcf.setCapitalBalance(bo.getOrderBalance());

			// 创建时间
			bcf.setCreateTime(DateCompareUtil.getNowDate());

			// 1:成功 2:失败
			bcf.setStatus(1);
			washerFunddetailsMapper.insertByEntity(bcf);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 洗车工账户总资金信息-减少
	 * 
	 * @param map
	 * @return
	 */
	public boolean updateWasherFundstatisticsReduce(BussUserOrder bo) {
		try {
			Map<String, Object> reap = new HashMap<String, Object>();
			Map<String, Object> resultMaps = new HashMap<String, Object>();
			BussWasherFundstatistics bcf = new BussWasherFundstatistics();
			bcf.setWasherId(Long.valueOf(bo.getWasherId()));
			bcf = washerFundstatisticsMapper.selectSingle(bcf);
			if (bcf != null) {
				long balance = bcf.getBalance();
				if (balance < bo.getOrderBalance()) {
					return false;
				}
				// 当为洗车时
				long expenditure_balance = bcf.getExpenditureBalance();
				expenditure_balance = expenditure_balance + bo.getOrderBalance();
				// //总金额-已经将赠送金额算入总金额里面

				balance = balance - bo.getOrderBalance();
				bcf.setBalance(balance);

				bcf.setUpdateTime(DateCompareUtil.getNowDate());
				washerFundstatisticsMapper.updateByEntity(bcf);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return true;
	}

	/**
	 * 资金明细信息
	 * 
	 * @param map
	 * @return
	 */
	public void createUserFunddetails(BussUserOrder bo, int type) {

		try {
			BussUserFunddetails bcf = new BussUserFunddetails();
			bcf.setObjectId(Integer.valueOf(bo.getUserId().toString()));
			bcf.setOrderId(Integer.valueOf(bo.getId().toString()));

			// 资金明细类型（1-充值；2-优惠券收入；3-退款收入；11-购物支出；21-优惠券支出；31-打赏支出；）
			if (type == 1) {
				bcf.setCapitalType(1);
			} else if (type == 2) {
				bcf.setCapitalType(2);
			} else if (type == 3) {
				bcf.setCapitalType(3);
			} else if (type == 11) {
				bcf.setCapitalType(11);
			} else if (type == 21) {
				bcf.setCapitalType(21);
			} else if (type == 31) {
				bcf.setCapitalType(31);
			}

			// 交易时间
			bcf.setTransactionTime(DateCompareUtil.getNowDate());

			// 交易金额
			long capitalBalance = bo.getOrderBalance();
			bcf.setCapitalBalance(capitalBalance);

			// 赠送金额
			bcf.setGiveBalance(0L);

			// 创建时间
			bcf.setCreateTime(DateCompareUtil.getNowDate());

			// 1:成功 2:失败
			bcf.setStatus(1);
			userFunddetailsMapper.insertByEntity(bcf);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 账户总资金信息-增加
	 * 
	 * @param map
	 * @return
	 */
	public void updateUserFundstatisticsAdd(BussUserOrder bo, int userType) {
		try {
			BussUserFundstatistics bcf = new BussUserFundstatistics();
			bcf.setObjectId(bo.getUserId());
			bcf = userFundstatisticsMapper.selectSingle(bcf);
			if (bcf != null) {
				long balance = bcf.getBalance();
				long give_balance = bcf.getGiveBalance();
				// 当为充值时
				if (userType == 1) {
					// 赠送金额
					give_balance = give_balance + bo.getOrderBalance();
					bcf.setGiveBalance(give_balance);
					balance = balance + bo.getOrderBalance();
				}

				// 总收入金额
				long recharge_balance = bcf.getRechargeBalance();
				recharge_balance = recharge_balance + bo.getOrderBalance();
				bcf.setRechargeBalance(recharge_balance);

				// //总金额-已经将赠送金额算入总金额里面
				balance = balance + bo.getOrderBalance();
				bcf.setBalance(balance);

				bcf.setUpdateTime(DateCompareUtil.getNowDate());
				userFundstatisticsMapper.updateByEntity(bcf);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 洗车工账户总资金信息-增加
	 * 
	 * @param map
	 * @return
	 */
	public void updateWasherFundstatisticsAdd(BussUserOrder bo, int type) {
		try {
			Map<String, Object> reap = new HashMap<String, Object>();
			BussWasherFundstatistics bcf = new BussWasherFundstatistics();
			bcf.setWasherId(Long.valueOf(bo.getWasherId().toString()));
			bcf = washerFundstatisticsMapper.selectSingle(bcf);
			if (bcf != null) {

				long washer_balance = bcf.getWasherBalance();
				long reward_balance = bcf.getRewardBalance();
				if (type == 1) {
					// 洗车时金额
					washer_balance = washer_balance + bo.getOrderBalance();
					bcf.setWasherBalance(washer_balance);
				} else if (type == 2) {
					// 打赏金额
					reward_balance = reward_balance + bo.getOrderBalance();
					bcf.setRewardBalance(reward_balance);
				}

				// //总金额-已经将赠送金额算入总金额里面
				long balance = bcf.getBalance();
				balance = balance + bo.getOrderBalance();
				bcf.setBalance(balance);

				bcf.setUpdateTime(DateCompareUtil.getNowDate());
				washerFundstatisticsMapper.updateByEntity(bcf);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 洗车工完成服务订单时候，资金变化
	 * 
	 * @return
	 */
	public void finishServiceMoney(BussUserOrder bo) {
		// 2. 创建用户明细表
		createWasherFunddetails(bo, 1);

		// 3. 修改用户资金总表信息
		// updateWasherFundstatisticsAdd(bo, 1);

	}

	@Override
	public PageObject<BussUserOrder> PageList(Map<String, Object> map) {
		map.put("sortName", "create_time");
		map.put("sortOrder", "desc");
		PageObject<BussUserOrder> page = super.Pagequery(map);
		List<BussUserOrder> list = page.getDataList();
		if (null != list && list.size() > 0) {
			for (BussUserOrder order : list) {
				Integer areaId = order.getAreaId();
				if (null != areaId) {
					String name = ucenterAreaService.getAreaName(areaId);
					order.setAreaName(name);
				}
			}
		}
		return page;
	}

	@Override
	public PageObject<BussUserOrder> pageQueryByForList(Map<String, Object> map) {
		map.put("sortName", "create_time");
		map.put("sortOrder", "desc");
		PageObject<BussUserOrder> page = super.Pagequery(map);
		List<BussUserOrder> list = page.getDataList();
		if (null != list && list.size() > 0) {
			for (BussUserOrder order : list) {
				Integer areaId = order.getAreaId();
				if (null != areaId) {
					String name = ucenterAreaService.getAreaName(areaId);
					order.setAreaName(name);
				}
			}
		}
		return page;
	}

	@Override
	public BussUserOrder findRoderInfo(Long id) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("id", id);
		BussUserOrder order = bussUserOrderMapper.findRoderInfo(map);
		if (null != order) {
			// 获取区域
			Integer areaId = order.getAreaId();
			if (null != areaId) {
				String name = ucenterAreaService.getAreaName(areaId);
				order.setAreaName(name);
			}
			// 服务项目
			if (order.getProjectId() != null) {
				String projectName = serviceProjectService.findProjectName(Long.valueOf(order.getProjectId()));
				order.setProjectName(projectName);
			}
			// 打赏
			if (order.getRewardId() != null) {
				BussUserReward b = userRewardService.findBussUserRewardInfo(order.getRewardId());
				order.setRewardBalance(b.getOrderBalance());
			}
			// 洗车工工号
			if (order.getWasherId() != null) {
				BussWasherInfo w = washerInfoService.findWasherInfo(order.getWasherId());
				order.setWasherJobnumber(w.getWasherJobnumber());
			}
		}
		return order;
	}

	@Override
	public void examine(Long id, Integer status) throws Exception {
		if (status == 2) {
			BussUserOrder b = new BussUserOrder();
			b.setId(id);
			BussUserOrder bo = bussUserOrderMapper.selectSingle(b);
			// 退款操作
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("washerId", bo.getWasherId());
			map.put("orderId", bo.getId());
			this.washerProessRefunds(map);

			// 对于用户和洗车工资金的处理
			// 2. 修改洗车工状态
			// bo.setExamineStatus(2);
			// bo.setOrderStatus(21);
			// bo.setLastUpdateTime(new Date());
			// bussUserOrderMapper.updateByEntity(bo);

			// 4. 创建用户明细表
			// createUserFunddetails(bo, 3);

			// 5. 修改用户资金总表信息
			// updateUserFundstatisticsAdd(bo, 2);
		} else {
			BussUserOrder b = new BussUserOrder();
			b.setId(id);
			b.setExamineStatus(3);
			b.setLastUpdateTime(new Date());
			bussUserOrderMapper.updateByEntity(b);
		}
	}

	@Override
	public void settlement() throws Exception {
		// 查询配置时间settlementTime
		SysConfigDictionary configTime = new SysConfigDictionary();
		configTime.setDictName("settlementTime");
		SysConfigDictionary cTime = sysConfigDictionaryMapper.selectSingle(configTime);
		String value = cTime.getDictValue();
		if (value == null) {
			return;
		}
		int day = Integer.valueOf(DateCompareUtil.getDateString("dd"));
		Integer ss = Integer.valueOf(value);
		if (ss != day) {
			return;
		}
		// 查询结算比例 washerProportion
		SysConfigDictionary config = new SysConfigDictionary();
		config.setDictName("washerProportion");
		SysConfigDictionary c = sysConfigDictionaryMapper.selectSingle(config);
		double washerP = Double.valueOf(c.getDictValue()) / 100;
		// 查询打赏分配比例 rewardProportion
		config.setDictName("rewardProportion");
		SysConfigDictionary c1 = sysConfigDictionaryMapper.selectSingle(config);
		double rewardP = Double.valueOf(c1.getDictValue()) / 100;
		// 结算上个月日期
		List<String> lst = DateCompareUtil.getDatStartAndEndDay();
		BussGeneralAccount a = new BussGeneralAccount();
		// 洗车结算
		washerSettlement(washerP, lst, a);

		// 打赏结算
		rewardSettlement(rewardP, lst, a);

		// 修改总账
		a.setEndTime(lst.get(1));
		a.setBalance(a.getRewardBalance() + a.getSuccesBalance());
		generalAccountMapper.updateAccount(a);
	}

	// 洗车
	public void washerSettlement(double washerP, List<String> lst, BussGeneralAccount a) {
		Map<String, Object> map = new HashMap<String, Object>();
		long accountBalacne = 0L; // 洗车工结算
		map.put("end", lst.get(1));
		map.put("start", lst.get(0));
		List<BussUserOrder> orderList = bussUserOrderMapper.findBussUserOrderList(map);
		int refundNum = 0; // 退款订单个数
		long refundBalance = 0L; // 退款订单金额
		int successNum = 0; // 成功支付个数
		long succesBalance = 0L; // 成功支付订单总额
		long giveBalance = 0L; // 赠送金额
		for (BussUserOrder o : orderList) {
			if (o.getOrderStatus() == 21) {
				refundNum += 1;
				refundBalance = refundBalance + o.getRechargeBalance();
				continue;
			}
			successNum += 1;
			succesBalance = succesBalance + o.getRechargeBalance();
			giveBalance = giveBalance + o.getGiveBalance();
			// 处理订单列表状态
			BussUserOrder order = new BussUserOrder();
			order.setId(o.getId());
			order.setOrderStatus(30);
			order.setLastUpdateTime(new Date());
			bussUserOrderMapper.updateByEntity(order);
			// 生成洗车工订单
			BussWasherFunddetails washer = new BussWasherFunddetails();
			washer.setWasherId(o.getWasherId());
			washer.setOrderId(o.getId());
			washer.setCapitalType(1);
			washer.setCreateTime(new Date());
			washer.setTransactionTime(new Date());
			washer.setStatus(1);
			washer.setGiveBalance(o.getGiveBalance());
			washer.setPayBalance(o.getRechargeBalance());
			long money = (long) (o.getRechargeBalance() * washerP);
			washer.setCapitalBalance(money);
			bussWasherFunddetailsMapper.insertByEntity(washer);
			accountBalacne = accountBalacne + money;
			// 修改洗车工总账号
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("washerId", o.getWasherId());
			params.put("money", money);
			params.put("updateTime", new Date());
			washerFundstatisticsMapper.updateWasherMoney(params);
		}
		a.setWasherBalance(accountBalacne);
		a.setRefundNum(refundNum);
		a.setRefundBalance(refundBalance);
		a.setGiveBalance(giveBalance);
		a.setSuccesBalance(succesBalance);
		a.setSuccessNum(successNum);
	}

	// 打赏结算
	public void rewardSettlement(double rewardP, List<String> lst, BussGeneralAccount a) {
		long accountBalacne = 0L;
		int num = 0;
		long total = 0L;
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("end", lst.get(1));
		map.put("start", lst.get(0));
		List<BussUserReward> list = bussUserRewardMapper.findList(map);
		for (BussUserReward o : list) {
			// 处理订单列表状态
			BussUserReward order = new BussUserReward();
			order.setId(o.getId());
			order.setOrderStatus(4);
			order.setLastUpdateTime(new Date());
			bussUserRewardMapper.updateByEntity(order);
			// 生成洗车工订单
			BussWasherFunddetails washer = new BussWasherFunddetails();
			washer.setWasherId(o.getWasherId());
			washer.setOrderId(Long.valueOf(o.getId()));
			washer.setCapitalType(2);
			washer.setCreateTime(new Date());
			washer.setTransactionTime(new Date());
			washer.setStatus(1);
			washer.setPayBalance(o.getOrderBalance());
			long money = (long) (o.getOrderBalance() * rewardP);
			washer.setCapitalBalance(money);
			bussWasherFunddetailsMapper.insertByEntity(washer);
			num += 1;
			accountBalacne = accountBalacne + money;
			total = total + o.getOrderBalance();
			// 修改洗车工总账号
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("washerId", o.getWasherId());
			params.put("money", money);
			params.put("updateTime", new Date());
			washerFundstatisticsMapper.updateRewardMoney(params);
		}
		a.setRewardNum(num); // 打赏个数
		a.setRewardBalance(total); // 打赏总额
		a.setSuccessRewardB(accountBalacne); // 打赏结算
	}

	// 循环次数
	public int num(int total) {
		if (total % 20 == 0) {
			return total / 20;
		} else {
			return total / 20 + 1;
		}
	}

	/**
	 * 资金明细信息
	 * 
	 * @param map
	 * @return
	 */
	public boolean createUserFunddetails(long orderBalance, long giveBalance, int userId, int orderId, int type) {
		try {
			BussUserFunddetails bcf = new BussUserFunddetails();
			bcf.setObjectId(userId);
			bcf.setOrderId(orderId);

			// 资金明细类型（1-充值；2-优惠券收入；3-退款收入；11-购物支出；21-优惠券支出；31-打赏支出；）
			if (type == 1) {
				bcf.setCapitalType(1);
			} else if (type == 2) {
				bcf.setCapitalType(2);
			} else if (type == 3) {
				bcf.setCapitalType(3);
			} else if (type == 11) {
				bcf.setCapitalType(11);
			} else if (type == 21) {
				bcf.setCapitalType(21);
			} else if (type == 31) {
				bcf.setCapitalType(31);
			}

			// 交易时间
			bcf.setTransactionTime(DateCompareUtil.getNowDate());

			// 交易金额
			// long capitalBalance =
			// Long.valueOf(map.get("orderBalance").toString());
			bcf.setCapitalBalance(orderBalance);

			// 赠送金额
			bcf.setGiveBalance(giveBalance);

			// 创建时间
			bcf.setCreateTime(DateCompareUtil.getNowDate());

			// 1:成功 2:失败
			bcf.setStatus(1);

			userFunddetailsMapper.insertByEntity(bcf);

			return true;
		} catch (Exception e) {
			e.printStackTrace();
		}

		return false;
	}

	/**
	 * 账户总资金信息-减少
	 * 
	 * @param map
	 * @return
	 */
	public boolean updateUserFundstatisticsReduce(long orderBalance, int userId) {

		try {
			Map<String, Object> reap = new HashMap<String, Object>();
			reap.put("objectId", userId);
			BussUserFundstatistics bcf = new BussUserFundstatistics();
			bcf.setObjectId(Long.valueOf(userId));
			bcf = userFundstatisticsMapper.selectSingle(bcf);
			if (bcf != null) {
				// //总金额-已经将赠送金额算入总金额里面
				long balance = bcf.getBalance();
				if (balance < orderBalance) {
					return false;
				}

				// 总支出
				long reward_balance = bcf.getRewardBalance();
				reward_balance = reward_balance + orderBalance;
				bcf.setRewardBalance(reward_balance);

				balance = balance - orderBalance;
				bcf.setBalance(balance);

				bcf.setUpdateTime(DateCompareUtil.getNowDate());
				userFundstatisticsMapper.updateByEntity(bcf);
				return true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	@Override
	public void handleUserRechargeMoney(BussUserConsumorder bo) {
		// 2. 创建用户明细表
		createUserFunddetails(bo.getOrderBalance(), bo.getGiveBalance(), Integer.valueOf(bo.getUserId().toString()),
				Integer.valueOf(bo.getId().toString()), 1);
		// 3. 修改用户资金总表信息
		updateUserFundstatisticsAdd(bo, 1);
	}

	/**
	 * 微信购买，对资金总账户不变，只添加明细
	 */
	public void userWXRechargeMoney(BussUserOrder bo) {
		// 2. 创建用户明细表
		createUserFunddetails(bo.getOrderBalance(), bo.getGiveBalance(), Integer.valueOf(bo.getUserId().toString()),
				Integer.valueOf(bo.getId().toString()), 1);
	}

	/**
	 * 账户总资金信息-增加
	 * 
	 * @param map
	 * @return
	 */
	public void updateUserFundstatisticsAdd(BussUserConsumorder bo, int userType) {
		try {
			BussUserFundstatistics bcf = new BussUserFundstatistics();
			if (bo.getUserId() != null) {
				bcf.setObjectId(bo.getUserId());
			}
			bcf = userFundstatisticsMapper.selectSingle(bcf);
			if (bcf != null) {
				long balance = bcf.getBalance();
				long give_balance = bcf.getGiveBalance();
				
				long give_balance_new= 0L; 
				long balance_new = 0L;
				long recharge_balance_new = 0L;
				// 当为充值时
				if (userType == 1) {
					// 赠送金额
					give_balance_new = give_balance + bo.getGiveBalance();
					bcf.setGiveBalance(give_balance_new);
					balance_new = balance + bo.getOrderBalance() + give_balance;
				}

				// 总收入金额
				long recharge_balance = bcf.getRechargeBalance();
				recharge_balance_new = recharge_balance + bo.getOrderBalance();
				bcf.setRechargeBalance(recharge_balance_new);

				// //总金额-已经将赠送金额算入总金额里面
				bcf.setBalance(balance_new);

				bcf.setUpdateTime(DateCompareUtil.getNowDate());
				userFundstatisticsMapper.updateByEntity(bcf);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 用户打赏微信支付金额变更
	 */
	public void handleUserRewardMoney(BussUserReward br) {
		// 2. 创建一条明细记录(用户表减少资金)
		// 资金明细类型（1-充值；2-优惠券收入；3-退款收入；11-购物支出；21-优惠券支出；31-打赏支出；）
		createUserFunddetails(br.getOrderBalance(), 0, Integer.valueOf(br.getUserId().toString()), br.getId(), 31);

		// 3. 创建一条明细记录（洗车工增加资金）
		createWasherFunddetails(br.getOrderBalance(), br.getWasherId(), br.getId(), 2);
	}

	/**
	 * 用户打赏微信支付金额变更
	 */
	// public void handleUserRewardMoney(BussUserReward br) {
	//
	// // 2. 创建一条明细记录(用户表减少资金)
	// // 资金明细类型（1-充值；2-优惠券收入；3-退款收入；11-购物支出；21-优惠券支出；31-打赏支出；）
	// // createUserFunddetails(br.getOrderBalance(),
	// // Integer.valueOf(br.getUserId().toString()), br.getId(), 31);
	//
	// // 3. 创建一条明细记录（洗车工增加资金）
	// createWasherFunddetails(br.getOrderBalance(), br.getWasherId(),
	// br.getId(), 2);
	//
	// // 4. 更新用户资金总表记录(用户表减少资金)
	// updateUserFundstatisticsReduce(br.getOrderBalance(),
	// Integer.valueOf(br.getUserId().toString()));
	//
	// // 5. 洗车工资金总表记录（洗车工增加资金）
	// // updateWasherFundstatisticsAdd(br.getOrderBalance(), 2,
	// // br.getWasherId());
	//
	// }

	/**
	 * 洗车工资金明细信息
	 * 
	 * @param map
	 * @return
	 */
	public void createWasherFunddetails(long orderBalance, int userId, int orderId, int type) {

		try {
			BussWasherFunddetails bcf = new BussWasherFunddetails();
			bcf.setWasherId(userId);
			bcf.setOrderId(Long.valueOf(orderId));

			// 资金明细类型（1-洗车收入；2-打赏收入；10-提现支出；12-退款支出；）
			if (type == 1) {
				bcf.setCapitalType(1);
			} else if (type == 2) {
				bcf.setCapitalType(2);
			} else if (type == 10) {
				bcf.setCapitalType(10);
			} else if (type == 11) {
				bcf.setCapitalType(11);
			}

			// 交易时间
			bcf.setTransactionTime(DateCompareUtil.getNowDate());

			// 交易金额
			bcf.setCapitalBalance(orderBalance);

			// 创建时间
			bcf.setCreateTime(DateCompareUtil.getNowDate());

			// 1:成功 2:失败
			bcf.setStatus(1);
			washerFunddetailsMapper.insertByEntity(bcf);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 洗车工账户总资金信息-增加
	 * 
	 * @param map
	 * @return
	 */
	public void updateWasherFundstatisticsAdd(long orderBalance, int userType, int userId) {
		try {
			Map<String, Object> reap = new HashMap<String, Object>();
			BussWasherFundstatistics bcf = new BussWasherFundstatistics();
			bcf.setWasherId(Long.valueOf(userId));
			bcf = washerFundstatisticsMapper.selectSingle(bcf);
			if (bcf != null) {

				long washer_balance = bcf.getWasherBalance();
				long reward_balance = bcf.getRewardBalance();
				if (userType == 1) {
					// 洗车时金额
					washer_balance = washer_balance + orderBalance;
					bcf.setWasherBalance(washer_balance);
				} else if (userType == 2) {
					// 打赏金额
					reward_balance = reward_balance + orderBalance;
					bcf.setRewardBalance(reward_balance);
					;
				}

				// //总金额-已经将赠送金额算入总金额里面
				long balance = bcf.getBalance();
				balance = balance + orderBalance;
				bcf.setBalance(balance);

				bcf.setUpdateTime(DateCompareUtil.getNowDate());
				washerFundstatisticsMapper.updateByEntity(bcf);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public int getRefundsCountByWasher(Map<String, Object> map) {
		return bussUserOrderMapper.getRefundsCountByWasher(map);
	}

	/**
	 * 用户退款业务处理
	 * 
	 * @param map
	 * @throws ClientException
	 */
	@Transactional(propagation = Propagation.REQUIRED)
	public int modifyRefunds(Map<String, Object> map) throws ClientException {
		BussUserOrder b = new BussUserOrder();
		b.setId(Long.valueOf(map.get("id").toString()));
		b.setUserId(Long.valueOf(map.get("userId").toString()));
		b.setOrderStatus(3);
		BussUserOrder bo = bussUserOrderMapper.selectSingle(b);
		if (bo != null) {
			Map<String, Object> rm = DateCompareUtil.getMonthFirstLast();
			rm.put("washerId", bo.getWasherId());
			int count = getRefundsCountByWasher(rm);
			if (count >= 3) {
				bo.setExamineStatus(1); // 退款申请审核（系统管理员）（-1;洗车工审核；0-不用审核；1-等待管理员审核；2-通过；3-不通过）
			} else {
				bo.setExamineStatus(-1); // 退款申请审核（系统管理员）（-1;洗车工审核；0-不用审核；1-等待管理员审核；2-通过；3-不通过）
			}

			bo.setOrderStatus(20); // 订单状态(1-未开始；2-开始服务；3-服务完成；10-订单取消；20-申请退款;21-完成退款；30-已结算)

			bussUserOrderMapper.updateByEntity(bo);

			BussWasherInfo wsr = new BussWasherInfo();
			wsr.setId(bo.getWasherId());
			wsr = washerInfoMapper.selectSingle(wsr);
			if (wsr != null) {

				try {
					// 发送短信通知，用户退单
					refundsOrdNotice(wsr.getWasherMobile(), wsr.getWasherNick(), bo.getOrderNo(),
							DateCompareUtil.getDateToString(bo.getBespokeBeginTime()));

					messageService.addMessage(2, "2", "订单通知",
							"尊敬的 " + wsr.getWasherRealname() + "，您的 订单  " + bo.getOrderNo() + " 已经被用户退单，请及时处理，谢谢！",
							wsr.getId().toString());

					messageService.addMessage(1, "2", "订单通知",
							"尊敬的 " + bo.getLinkMan() + "，您的 订单单 " + bo.getOrderNo() + " 已经提交成功，我们将安排洗车工核实并处理，请耐心等待，谢谢！",
							bo.getUserId().toString());
				} catch (Exception e) {
					LOGGER.error("订单支付-微信支付发送站内信息或者短信失败，订单号为 ： " + bo.getOrderNo());
				}

			}
			return 0;
		} else {
			return -1;
		}
	}

	public boolean refundsOrdNotice(String phoneNumber, String name, String orderCode, String orderTime)
			throws ClientException {

		boolean rs = SmsUtils.refundsOrdNotice(phoneNumber, name, orderCode, orderTime);
		return rs;
	}

	/**
	 * 对于用户使用余额进行订单购买 返回数据： 0-成功；T-用户订单不存在；N-账户余额不足 ； F- 分配订单失败; -1-失败
	 * 
	 * @throws ClientException
	 */
	// @Transactional(propagation = Propagation.REQUIRED)
	// public String createAccountOrder(Map<String, Object> map) throws
	// ClientException {
	// // 1.获取到订单信息，更新订单支付状态，变更用户资金明细，分配订单给洗车工
	// // BussUserOrder vo = new BussUserOrder();
	// // vo.setId(Long.valueOf(map.get("id").toString()));
	// long userId = Long.valueOf(map.get("userId").toString());
	// // 获取用户账户，查询是否有足够的资金进行支付
	// BussUserFundstatistics bcf = new BussUserFundstatistics();
	// bcf.setObjectId(userId);
	// bcf = userFundstatisticsMapper.selectSingle(bcf);
	//
	// // 对支付的金额进行分配（充值金额和赠送金额）
	// if (bcf != null) {
	// long orderBalance = Long.valueOf(map.get("orderBalance").toString());
	// if (bcf.getBalance() >= orderBalance) {
	// long giveBalance = bcf.getGiveBalance();
	// long rechargebalance = bcf.getRechargeBalance();
	//
	// long regiveBalance = 0l;
	// long rerechargebalance = 0l;
	//
	// if (rechargebalance - orderBalance / 2 >= 0) {
	// if (giveBalance - orderBalance / 2 >= 0) {
	// // 充值金额 和 赠送金额各个减订单金额一半
	// regiveBalance = orderBalance / 2;
	// rerechargebalance = orderBalance / 2;
	// } else {
	// long bl = orderBalance - giveBalance;
	// // 充值金额减去 bl
	// regiveBalance = bl;
	// rerechargebalance = orderBalance - bl;
	// }
	// } else {
	// long bl = orderBalance - rechargebalance;
	// // 赠送金额减去 bl
	// rechargebalance = bl;
	// regiveBalance = orderBalance - bl;
	// }
	//
	// map.put("orderBalance", rerechargebalance);
	// map.put("giveBalance", regiveBalance);
	//
	// String orderNo = consumorderService.createConsumOrderVo(map, 1, 2);
	// createOrderInfo(map, orderNo);
	// return orderNo;
	// } else {
	// return "N";
	// }
	// } else {
	// return null;
	// }
	// }

	/**
	 * 对于用户使用余额进行订单购买 返回数据： 0-成功；1-用户订单不存在；2-账户余额不足 ； 3- 分配订单失败; 4-密码错误
	 * 
	 * @throws ClientException
	 */
	@Transactional(propagation = Propagation.REQUIRED)
	public int payAccountOrder(Map<String, Object> map) throws ClientException {
		// 1.获取到订单信息，更新订单支付状态，变更用户资金明细，分配订单给洗车工
		BussUserOrder vo = new BussUserOrder();
		vo.setOrderNo(map.get("orderNo").toString());
		long userId = Long.valueOf(map.get("userId").toString());
		vo.setUserId(userId);

		// 验证支付密码是否正确
		BussUserInfo bi = new BussUserInfo();
		bi.setId(Integer.valueOf(map.get("userId").toString()));
		bi = userInfoMapper.selectSingle(bi);
		String userPaypwd = map.get("userPaypwd").toString();
		userPaypwd = PasswordEncoder.getPassword(userPaypwd);
		if (bi != null) {
			String payPassword = bi.getUserPaypwd();
			if (!StringUtils.isEmpty(payPassword)) {
				if (payPassword.equals(userPaypwd)) {
					// 获取用户账户，查询是否有足够的资金进行支付
					BussUserFundstatistics bcf = new BussUserFundstatistics();
					bcf.setObjectId(userId);
					bcf = userFundstatisticsMapper.selectSingle(bcf);
					vo = bussUserOrderMapper.selectSingle(vo);

					long orderBalance = vo.getOrderBalance();
					if (bcf != null && vo != null && vo.getPayStatus() != 2) {
						if (bcf.getBalance() >= orderBalance) {
							long giveBalance = bcf.getGiveBalance();
							long rechargebalance = bcf.getRechargeBalance();

							long regiveBalance = 0l; // 赠送金额
							long rerechargebalance = 0l; // 充值金额

							if (orderBalance % 2 == 0) {
								if (rechargebalance - orderBalance * 0.5 >= 0) {
									if (giveBalance - orderBalance * 0.5 >= 0) {
										// 充值金额 和 赠送金额各个减订单金额一半
										regiveBalance = orderBalance / 2;
										rerechargebalance = orderBalance / 2;
									} else {
										regiveBalance = giveBalance;
										rerechargebalance = orderBalance - giveBalance;
									}
								} else {
									rerechargebalance = rechargebalance;
									regiveBalance = orderBalance - rechargebalance;
								}
							} else {
								if (rechargebalance - orderBalance > 0) {
									rerechargebalance = orderBalance;
									regiveBalance = 0;
								} else {
									rerechargebalance = rechargebalance;
									regiveBalance = orderBalance - rechargebalance;
								}
							}

							vo.setRechargeBalance(rerechargebalance);
							vo.setGiveBalance(regiveBalance);
						} else {
							return 2;
						}
						// 分配洗车工
						int washerId = createDispatchOrder(vo);
						if (washerId > 0) {

							// 更新订单支付状态
							vo.setWasherId(washerId);
							vo.setOrderIsassign(1);
							vo.setPayStatus(2);
							vo.setOrderStatus(1);
							bussUserOrderMapper.updateByEntity(vo);

							// 创建订单后，对于用户的账户资金进行修改
							handleUserCreateOrderMoney(vo);

							// 给洗车工发送短信通知
							BussWasherInfo ws = new BussWasherInfo();
							ws.setId(washerId);
							ws = washerInfoMapper.selectSingle(ws);
							if (ws != null) {
								try {
									// 发送短信给洗车工
									SmsUtils.sendOrdNotice(ws.getWasherMobile(), ws.getWasherRealname(),
											vo.getOrderNo(), DateCompareUtil.getDateToString(vo.getBespokeBeginTime())
													+ "-" + DateCompareUtil.getDateToMils(vo.getBespokeEndTime()));
									// 发站内信息给用户
									messageService.addMessage(1, "2", "订单支付成功", "尊敬的 " + vo.getLinkMan() + "，您的爱车"
											+ vo.getCarCode() + "，已预约洗车成功，感谢您对本平台的支持！", vo.getUserId().toString());

									// 发站内信息给洗车工
									messageService.addMessage(1, "2", "新订单通知",
											"尊敬的 " + ws.getWasherRealname() + "，您有新的订单产生，订单号为 ：" + vo.getOrderNo()
													+ "，服务时间"
													+ DateCompareUtil.getDateToString(vo.getBespokeBeginTime()) + "-"
													+ DateCompareUtil.getDateToMils(vo.getBespokeEndTime())
													+ "，请按时为客户服务" + "，谢谢！",
											String.valueOf(washerId));
									// 用户发送短信
									SmsUtils.sendCreateOrder(ws.getWasherMobile(),vo.getLinkMan());
								} catch (Exception e) {
									LOGGER.error("发送短信或者创建站内消息失败！ 订单号为 ： " + vo.getOrderNo());
								}
							}
							return 0;
						} else {
							return 3;
						}
					} else {
						return 1;
					}
				} else {
					return 5;
				}
			} else {
				return 4;
			}
		} else {
			return 1;
		}
	}

	/**
	 * 对于余额支付后对账户资金变化情况
	 * 
	 * @param bo
	 * @param rechargebalance
	 * @param giveBalance
	 */
	public void handleUserCreateOrderMoney(BussUserOrder bo) {
		// 2. 创建用户明细表
		createUserFunddetails(bo.getOrderBalance(), bo.getGiveBalance(), Integer.valueOf(bo.getUserId().toString()),
				Integer.valueOf(bo.getId().toString()), 11);

		// 3. 修改用户资金总表信息
		updateUserFundstatisticsReduce(bo.getOrderBalance(), Integer.valueOf(bo.getUserId().toString()),
				bo.getRechargeBalance(), bo.getGiveBalance());
	}

	/**
	 * 账户总资金信息-减少
	 * 
	 * @param map
	 * @return
	 */
	public boolean updateUserFundstatisticsReduce(long orderBalance, int userId, long rechargebalance,
			long giveBalance) {

		try {
			Map<String, Object> reap = new HashMap<String, Object>();
			reap.put("objectId", userId);
			BussUserFundstatistics bcf = new BussUserFundstatistics();
			bcf.setObjectId(Long.valueOf(userId));
			bcf = userFundstatisticsMapper.selectSingle(bcf);
			if (bcf != null) {
				// //总金额-已经将赠送金额算入总金额里面
				long balance = bcf.getBalance();
				if (balance < orderBalance) {
					return false;
				}

				// 总支出
				long reward_balance = bcf.getRewardBalance();
				reward_balance = reward_balance + orderBalance;
				bcf.setRewardBalance(reward_balance);

				balance = balance - orderBalance;
				bcf.setBalance(balance);
				bcf.setRechargeBalance(bcf.getRechargeBalance() - rechargebalance);
				bcf.setGiveBalance(bcf.getGiveBalance() - giveBalance);

				bcf.setUpdateTime(DateCompareUtil.getNowDate());
				userFundstatisticsMapper.updateByEntity(bcf);
				return true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	/**
	 * 进行有效时间选择
	 * 
	 * @param map
	 * @return null 就是附近没有可以服务的洗车工或者洗车工已经休假了
	 */
	public Map<String, Object> choiceTimes(Map<String, Object> map) {

		long projectId = Long.valueOf(map.get("projectId").toString());
		int areaId = Integer.valueOf(map.get("areaId").toString());
		String reservationDate = map.get("reservationDate").toString();
		Map<String, Object> resultMaps = new HashMap<String, Object>();

		// 不可预约
		List<String> connotMaps = new ArrayList<String>();

		// 可以预约
		List<String> sureMaps = new ArrayList<String>();

		// 获取小区存正的洗车工，都是已经签到的洗车工
		List<BussWasherSgin> ws = getBussWasherInfos(areaId, reservationDate);
		if (ws != null && ws.size() > 0) {
			BussServiceProject bsp = new BussServiceProject();
			bsp.setId(projectId);
			bsp = serviceProjectMapper.selectSingle(bsp);
			int projectTimes = 0;
			if (bsp != null) {
				projectTimes = Integer.valueOf(bsp.getProjectTimes());
			}
			// 获取小区存正的洗车工，都是已经签到的洗车工已经产生的订单
			Map<String, Object> lis = getBussWasherOrders(projectTimes, areaId, reservationDate, map);
			if (lis != null && lis.size() > 0) {
				return lis;
			}
		} else {
			resultMaps.put("sure", sureMaps);
			resultMaps.put("cannot", connotMaps);
			return resultMaps;
		}
		return resultMaps;
	}

	/**
	 * 获取可以使用的洗车工
	 * 
	 * @return
	 */
	public List<BussWasherSgin> getBussWasherInfos(int areaId, String reservationDate) {
		// 1.先通过地区ID获取附近的洗车工
		BussWasherInfo w = new BussWasherInfo();
		w.setAreaId(areaId);
		w.setWasherIsdeposit(1);
		w.setWasherIsEntrust(1);
		w.setWasherExamine(1);
		List<BussWasherInfo> ws = washerInfoMapper.selectByObject(w);
		if (ws != null && ws.size() > 0) {
			List<BussWasherSgin> bwi = new ArrayList<BussWasherSgin>();

			// 获取洗车工所有的预约
			for (BussWasherInfo bw : ws) {
				// 查询洗车是否已经签到
				BussWasherSgin wss = new BussWasherSgin();
				Date da = DateCompareUtil.stringToDate(reservationDate);
				wss.setWasherId(bw.getId());
				wss.setSginDate(DateCompareUtil.getDateToDateString(da));
				wss = washerSginMapper.selectSingle(wss);
				if (wss != null && wss.getId() != null) {

					bwi.add(wss);
				}
			}

			return bwi;
		} else {
			return null;
		}
	}

	/**
	 * 获取可以使用的洗车工
	 * 
	 * @return
	 */
	public Map<String, Object> getBussWasherOrders(int times, int areaId, String reservationDate,
			Map<String, Object> map) {
		Date beginDate = DateCompareUtil.getNowDate(reservationDate + " 9:00:00");
		Date endDate = DateCompareUtil.getNowDate(reservationDate + " 21:00:00");
		Map<String, Object> result = getSystemTimes(times, reservationDate);
		Map<String, Object> results = new HashMap<String, Object>();
		// 不可预约
		List<String> connotMaps = new ArrayList<String>();
		// List<String> newconnotMaps = new ArrayList<String>();
		if (result.get("connot") != null) {
			connotMaps = (List<String>) result.get("connot");
		}
		// 可以预约
		List<String> newsureMaps = new ArrayList<String>();
		List<String> sureMaps = new ArrayList<String>();
		if (result.get("sure") != null) {
			sureMaps = (List<String>) result.get("sure");
		}

		// 获取洗车工，并且都是经过打卡的
		if (sureMaps != null && sureMaps.size() > 0) {
			// 对于用户 打卡进行筛选
			List<BussWasherSgin> bwi = getBussWasherInfos(areaId, reservationDate);
			if (bwi != null && bwi.size() > 0) {
				for (int i = 0; i < sureMaps.size(); i++) {
					String sure = sureMaps.get(i);
					int count = 1;
					for (BussWasherSgin bs : bwi) {
						// 上午签到
						String sgin_morning = bs.getSginMorning();
						// 下午签到
						String sgin_afternoon = bs.getSginAfternoon();
						if (!StringUtils.isEmpty(sgin_morning) && !StringUtils.isEmpty(sgin_afternoon)) {
							if (DateCompareUtil.isInTime(sgin_morning, sure)
									|| DateCompareUtil.isInTime(sgin_afternoon, sure)) {
								count = count + 1;
							}
						} else if (!StringUtils.isEmpty(sgin_morning)) {
							if (DateCompareUtil.isInTime(sgin_morning, sure)) {
								count = count + 1;
							}
						} else if (!StringUtils.isEmpty(sgin_afternoon)) {
							if (DateCompareUtil.isInTime(sgin_afternoon, sure)) {
								count = count + 1;
							}
						}
					}

					if (count > 1) {
						newsureMaps.add(sure);
					} else {
						// newconnotMaps.add(sure);
						connotMaps.add(sure);
					}
				}

				List<String> nnewconnotMaps = new ArrayList<String>();
				// 对于用户 订单进行筛选
				if (bwi != null && bwi.size() > 0) {
					for (int i = 0; i < newsureMaps.size(); i++) {
						String sure = newsureMaps.get(i);
						int count = 0;
						for (BussWasherSgin bs : bwi) {
							Map<String, Object> tmap = new HashMap<String, Object>();
							tmap.put("areaId", areaId);
							int washerId = bs.getWasherId();
							tmap.put("washerId", washerId);
							tmap.put("beginDate", beginDate);
							tmap.put("endDate", endDate);
							List<BussUserOrder> vos = bussUserOrderMapper.findOrderInfoBySpoke(tmap);
							if (vos != null && vos.size() > 0) {
								for (BussUserOrder bo : vos) {
									String rs = DateCompareUtil.getDayForHours(bo.getBespokeBeginTime(),
											bo.getBespokeEndTime());
									if (!StringUtils.isEmpty(rs)) {
										if (DateCompareUtil.isInTime(rs, sure)) {
											count = count + 1;
										}
									}
								}
							}
						}

						if (count == bwi.size()) {
							// newconnotMaps.add(sure);
							connotMaps.add(sure);
						} else {
							nnewconnotMaps.add(sure);
						}
					}
				}
				// results.put("connot", newconnotMaps);
				results.put("connot", connotMaps);
				results.put("sure", nnewconnotMaps);
				return results;
			} else {
				return result;
			}
		} else {
			return result;
		}
	}

	/**
	 * 获取可以使用的洗车工
	 * 
	 * @return
	 */
	public Map<String, Object> getSystemTimes(int times, String reservationDate) {

		Map<String, Object> result = new HashMap<String, Object>();

		// 不可预约
		List<String> connotMaps = new ArrayList<String>();

		// 可以预约
		List<String> sureMaps = new ArrayList<String>();

		Date da = DateCompareUtil.stringToDate(reservationDate);
		// 下单日就是当天
		if (DateCompareUtil.isToday(DateCompareUtil.getDateToString(reservationDate))) {
			// 最小的切割时间
			Date minDate_1 = DateCompareUtil.getNowDate(reservationDate + " 09:00:00");
			Date minDate_2 = DateCompareUtil.getNowDate(reservationDate + " 13:00:00");
			// 最大的切割时间
			Date maxDate_1 = DateCompareUtil.getNowDate(reservationDate + " 14:00:00");
			Date maxDate_2 = DateCompareUtil.getNowDate(reservationDate + " 21:00:00");
			// 现在的时间，
			Date nowDate = new Date();

			if (nowDate.getTime() < minDate_1.getTime()) {
				// 切割时间 从早上 09:00-13:00 14：00-21：00
				List<String> newmaps = DateCompareUtil.getDayForHoursForList(da, times);
				for (String s : newmaps) {
					sureMaps.add(s);
				}
			} else if ((maxDate_2.getTime() > nowDate.getTime()) && (nowDate.getTime() > minDate_1.getTime())) {
				// 切割时间 从早上 09:00-13:00 14：00-21：00
				if ((minDate_2.getTime() > nowDate.getTime()) && (nowDate.getTime() > minDate_1.getTime())) {
					// 切割时间从现在 9：00-现在（不可用） 开始 到 13：00 14：00-21：00
					Map<Integer, String> newmaps = DateCompareUtil.getDayForHoursByCustom(minDate_1, new Date(), times);
					if (newmaps != null) {
						for (Entry<Integer, String> en : newmaps.entrySet()) {
							connotMaps.add(en.getValue());
						}
					}
					// 开始 到 13：00 可用
					Map<Integer, String> newmapst = DateCompareUtil.getDayForHoursByCustom(minDate_2, new Date(),
							times);
					if (newmapst != null) {
						for (Entry<Integer, String> en : newmapst.entrySet()) {
							sureMaps.add(en.getValue());
						}
					}
					// 14：00-21：00 可用
					Map<Integer, String> anewmap = DateCompareUtil.getDayForHoursByAfternoon(maxDate_1, times);
					for (Map.Entry<Integer, String> entry : anewmap.entrySet()) {
						sureMaps.add(entry.getValue());
					}
				} else if ((maxDate_1.getTime() > nowDate.getTime()) && (nowDate.getTime() > minDate_2.getTime())) {
					// 切割时间从 9：00-13：00（不可用） 14：00-21：00
					Map<Integer, String> anewmap = DateCompareUtil.getDayForHours(maxDate_1, times);
					for (Map.Entry<Integer, String> entry : anewmap.entrySet()) {
						connotMaps.add(entry.getValue());
					}

					Map<Integer, String> anewmapt = DateCompareUtil.getDayForHoursByAfternoon(maxDate_1, times);
					for (Map.Entry<Integer, String> entry : anewmapt.entrySet()) {
						sureMaps.add(entry.getValue());
					}

				} else {
					// 切割时间从 9：00-13：00（不可用） 14：00-now(不可用) now-21：00
					Map<Integer, String> anewmap = DateCompareUtil.getDayForHours(maxDate_1, times);
					for (Map.Entry<Integer, String> entry : anewmap.entrySet()) {
						connotMaps.add(entry.getValue());
					}

					// 开始 到 13：00 可用
					Map<Integer, String> newmapst = DateCompareUtil.getDayForHoursByCustom(maxDate_1, new Date(),
							times);
					if (newmapst != null) {
						for (Entry<Integer, String> en : newmapst.entrySet()) {
							connotMaps.add(en.getValue());
						}
					}

					Map<Integer, String> newmapsa = DateCompareUtil.getDayForHoursByCustom(new Date(), maxDate_2,
							times);
					if (newmapst != null) {
						for (Entry<Integer, String> en : newmapsa.entrySet()) {
							sureMaps.add(en.getValue());
						}
					}
				}
			} else {
				// 切割时间 从早上 09:00-13:00 14：00-21：00
				List<String> newmaps = DateCompareUtil.getDayForHoursForList(da, times);
				for (String s : newmaps) {
					connotMaps.add(s);
				}
			}

		} else {
			// 切割时间 从早上 09:00-13:00 14：00-21：00
			List<String> newmaps = DateCompareUtil.getDayForHoursForList(da, times);
			for (String s : newmaps) {
				sureMaps.add(s);
			}
		}

		result.put("sure", sureMaps);
		result.put("connot", connotMaps);
		return result;
	}

	// /**
	// * 创建用户订单
	// */
	// @Transactional(propagation = Propagation.REQUIRED)
	// public Map<String, Object> createPurchaseOrder(Map<String, Object> map) {
	// int orderBalance = Integer.valueOf(map.get("orderBalance").toString());
	// // 3. 创建订单 ，进行订单判断，
	// String orderNo = consumorderService.createConsumOrderVo(map, 1, 2);
	// createOrderInfo(map, orderNo);
	// // 创建本地订单
	// if (!StringUtils.isEmpty(orderNo)) {
	// // 用户同意授权，获得的code
	// String code = map.get("openid").toString();
	//
	// // 调用统一下单service
	// WXOrderVO VO = new WXOrderVO();
	// VO.setBody("凤凰洗车-共享洗车服务");
	// VO.setOpenid(code);
	// VO.setOrderNo(orderNo);
	// VO.setNotityUrl(Constant.PUNOTIFY_URL);
	// VO.setOrderBalance(orderBalance);
	// Map<String, Object> maps = payService.unifiedOrder(VO);
	//
	// if (maps != null) {
	// // 修改订单支付单
	// BussUserConsumorder buc = new BussUserConsumorder();
	// buc.setOrderNo(orderNo);
	// buc = bussUserConsumorderMapper.selectSingle(buc);
	// if (buc != null) {
	//
	// buc.setServicesNo(maps.get("package").toString());
	// bussUserConsumorderMapper.updateByEntity(buc);
	// return maps;
	// }
	// }
	// } else {
	// return null;
	// }
	// return null;
	// }

	/**
	 * 创建用户订单
	 */
	@Transactional(propagation = Propagation.REQUIRED)
	public String createPurchaseOrders(Map<String, Object> map) {
		// 3. 创建订单 ，进行订单判断，
		String orderNo = consumorderService.createConsumOrderVo(map, 1, 2);
		createOrderInfo(map, orderNo);

		// 创建本地订单
		if (!StringUtils.isEmpty(orderNo)) {
			return orderNo;
		} else {
			return null;
		}
	}

	/**
	 * 添加用户车辆信息
	 * 
	 * @param orderVo
	 */
	public String createOrderInfo(Map<String, Object> map, String orderNo) {

		try {
			BussUserOrder buo = new BussUserOrder();
			buo.setUserId(Long.valueOf(map.get("userId").toString()));
			// buo.setConsumorderId(consumorderId); // 消费订单表id
			// 关联buss_user_consumorder表id
			buo.setOrderNo(orderNo);
			buo.setOrderName(map.get("orderName").toString());// 订单名称',
			buo.setOrderBalance(Long.valueOf(map.get("orderBalance").toString())); // 订单金额
			buo.setRechargeBalance(Long.valueOf(map.get("orderBalance").toString()));
			buo.setGiveBalance(0L);
			// 订单描述',
			if (map.get("orderDesc") != null) {
				buo.setOrderDesc(map.get("orderDesc").toString());
			}

			buo.setAreaId(Integer.valueOf(map.get("areaId").toString())); // 预约服务地址

			// 预约服务地址
			if (map.get("areaAddress") != null) {
				buo.setAreaAddress(map.get("areaAddress").toString());
			}

			buo.setCarCode(map.get("carCode").toString()); // 车牌号
			buo.setCarBrand(map.get("carBrand").toString());
			buo.setCarModel(map.get("carColor").toString());
			if (map.get("carModel") != null) {
				buo.setCarModel(map.get("carModel").toString());
			}

			// 车辆图片
			if (map.get("carImages") != null) {
				buo.setCarImages(map.get("carImages").toString());
			}

			buo.setBespokeBeginTime(DateCompareUtil.getNowDate(map.get("bespokeBeginTime").toString())); // 预约服务开始时间
			buo.setBespokeEndTime(DateCompareUtil.getNowDate(map.get("bespokeEndTime").toString())); // 预约服务结束时间

			buo.setLinkMan(map.get("linkMan").toString()); // 联系人
			buo.setLinkTel(map.get("linkTel").toString()); // 联系电话
			buo.setRechargeType(2); // 充值方式（1-微信支付；2-余额支付）
			buo.setTradeType(Integer.valueOf(map.get("tradeType").toString())); // 交易类型(1-公众号
																				// 2-APP;)',

			buo.setPayStatus(1); // '支付状态（1-未支付；2-已支付；3-失败；）

			buo.setOrderIsassign(2); // 是否分派(1-是；2-否)
			buo.setWasherId(null); // 洗车工ID'
			buo.setProjectId(map.get("objectsId").toString()); // 对应
																// sys_service_project
																// 的ID
			buo.setOrderIsevaluate(2); // 是否评价(1-是；2-否)
			buo.setOrderIsreward(2); // '是否打赏(1-是；2-否)',
			buo.setExamineStatus(0); // 退款申请审核（系统管理员）（0-不用审核；1-等待审核；2-通过；3-不通过）
			buo.setOrderStatus(-1);// 订单状态(1-未开始；2-开始服务；3-服务完成；10-订单取消；20-订单退款;30-已结算),
			buo.setCreateTime(DateCompareUtil.getNowDate());// 订单创建时间',
			buo.setCreateUserId(Long.valueOf(map.get("userId").toString()));// 创建用户id',
			bussUserOrderMapper.insertByEntity(buo);
			return orderNo;
		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}

	/**
	 * 用户充值订单回调接口
	 * 
	 * @param id
	 * @param map
	 * @return
	 * @throws ClientException
	 */
	@Transactional
	public boolean modifyPurchaseOrder(String transaction_id, String orderBalance, String orderNo)
			throws ClientException {
		// 1. 用户充值
		BussUserConsumorder buc = new BussUserConsumorder();
		buc.setOrderNo(orderNo);
		BussUserConsumorder cvo = bussUserConsumorderMapper.selectSingle(buc);
		if (cvo != null && orderBalance.equals(cvo.getOrderBalance().toString())) {
			if (cvo.getOrderStatus() != 2) {
				cvo.setOrderStatus(2);
				cvo.setFinishedStatus(2);
				cvo.setServicesNo(transaction_id);
				// 2. 对于用户充值后，对资金进行补充
				bussUserConsumorderMapper.updateByEntity(cvo);

				// 更新购买订单
				BussUserOrder buo = new BussUserOrder();
				buo.setOrderNo(orderNo);
				buo = bussUserOrderMapper.selectSingle(buo);
				if (buo != null) {

					// 分派订单
					int washerId = createDispatchOrder(buo);
					buo.setWasherId(washerId);
					buo.setPayStatus(2);
					buo.setOrderIsassign(1); // 已经分配
					buo.setOrderStatus(1);
					bussUserOrderMapper.updateByEntity(buo);
					// 处理用户资金
					userWXRechargeMoney(buo);

					try {
						// 给洗车工发送短信通知
						BussWasherInfo ws = new BussWasherInfo();
						ws.setId(washerId);
						ws = washerInfoMapper.selectSingle(ws);
						if (ws != null) {
							try {
								SmsUtils.sendOrdNotice(ws.getWasherMobile(), ws.getWasherRealname(), buo.getOrderNo(),
										DateCompareUtil.getDateToString(buo.getBespokeBeginTime()) + "-"
												+ DateCompareUtil.getDateToMils(buo.getBespokeEndTime()));
								LOGGER.debug("serevice times is :"
										+ DateCompareUtil.getDateToString(buo.getBespokeBeginTime()) + "-"
										+ DateCompareUtil.getDateToMils(buo.getBespokeEndTime()));
								messageService.addMessage(2, "2", "订单分派通知",
										"尊敬的 " + ws.getWasherRealname() + "，您的 新订单 " + orderNo + " 已经到达，请及时处理，谢谢！",
										buo.getUserId().toString());
								// 用户发送短信
								SmsUtils.sendCreateOrder(ws.getWasherMobile(),buo.getLinkMan());
								messageService.addMessage(1, "2", "订单通知", "尊敬的 " + buo.getLinkMan() + "，您创建的 订单 "
										+ orderNo + " 已经成功，我们将安排洗车工为您服务，请耐心等待，谢谢！", buo.getUserId().toString());
							} catch (Exception e) {
								LOGGER.error("订单支付-微信支付发送站内信息或者短信失败，订单号为 ： " + orderNo);
							}
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				return true;
			} else {
				return true;
			}

		} else {
			return false;
		}

	}

	/**
	 * 用户打赏订单
	 */
	public Map<String, Object> createRrewardOrder(Map<String, Object> map) {
		BussUserOrder buo = new BussUserOrder();
		buo.setOrderNo(map.get("orderNo").toString());
		buo = bussUserOrderMapper.selectSingle(buo);
		if (buo != null) {
			// 1. 先创建一条打赏订单记录
			long orderBalance = Long.valueOf(map.get("orderBalance").toString());
			String orderNo = createReward(buo, orderBalance);
			int payType = Integer.valueOf(map.get("payType").toString());
			// 创建本地订单
			if (!StringUtils.isEmpty(orderNo)) {
				if (payType == 1) {
					// 用户同意授权，获得的code
					String code = map.get("openid").toString();

					// 调用统一下单service
					WXOrderVO VO = new WXOrderVO();
					VO.setBody("凤凰洗车-共享洗车打赏服务");
					VO.setOpenid(code);
					VO.setOrderNo(orderNo);
					VO.setNotityUrl(Constant.PUNOTIFY_URL);
					VO.setOrderBalance(Integer.valueOf(map.get("orderBalance").toString()));
					Map<String, Object> maps = payService.unifiedOrder(VO);

					if (maps != null) {
						// 修改订单支付单
						BussUserReward br = new BussUserReward();
						br.setOrderNo(orderNo);
						br = bussUserRewardMapper.selectSingle(br);
						if (br != null) {

							br.setServicesNo(maps.get("package").toString());
							bussUserRewardMapper.updateByEntity(br);
							return maps;
						}
					}
				} else if (payType == 2) {
					// APP 支付
					// 调用统一下单service
					WXOrderVO VO = new WXOrderVO();
					VO.setBody("凤凰洗车-共享洗车打赏服务");
					VO.setOrderNo(orderNo);
					VO.setNotityUrl(Constant.PUNOTIFY_URL);
					VO.setOrderBalance(Integer.valueOf(map.get("orderBalance").toString()));
					Map<String, Object> maps = payService.unifiedOrderForApp(VO);

					if (maps != null) {
						// 修改订单支付单
						BussUserReward br = new BussUserReward();
						br.setOrderNo(orderNo);
						br = bussUserRewardMapper.selectSingle(br);
						if (br != null) {

							br.setServicesNo(maps.get("package").toString());
							bussUserRewardMapper.updateByEntity(br);
							return maps;
						}
					}
				}

			} else {
				return null;
			}
		}
		return null;
	}

	/**
	 * 添加打赏订单信息
	 * 
	 * @param map
	 * @return
	 */
	public String createReward(BussUserOrder bo, long orderBalance) {
		try {
			BussUserReward br = new BussUserReward();

			// 订单状态（1-打赏；）
			br.setOrderType(1);
			br.setUserId(bo.getUserId());
			String orderNo = String.valueOf(new SnowflakeIdWorker().nextId());
			br.setOrderNo(orderNo);
			br.setOrderBalance(orderBalance);
			// 对应 buss_user_order 的ID（打赏）
			br.setObjectsId(bo.getId().toString());

			br.setRechargeType(2); // 充值方式（1-微信支付；2-余额支付）
			br.setTradeType(1); // 交易类型(1-公众号 2-APP;)',

			// 订单完成状态（1-未完成；2-已完成；3-已失败；）
			br.setWasherId(bo.getWasherId());
			br.setOrderStatus(1);
			br.setCreateUserId(bo.getUserId());
			br.setCreateTime(DateCompareUtil.getNowDate());
			br.setSign(bo.getOrderNo());
			bussUserRewardMapper.insertByEntity(br);

			return orderNo;
		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}

	@Override
	public boolean modifyRrewardOrder(String transaction_id, String orderBalance, String orderNo) {
		BussUserReward bur = new BussUserReward();
		bur.setOrderNo(orderNo);
		bur = bussUserRewardMapper.selectSingle(bur);
		if (bur != null) {
			// 1.修改订单状态
			bur.setOrderStatus(2);
			bur.setServicesNo(transaction_id);
			bussUserRewardMapper.updateByEntity(bur);

			// 2.修改总订单状态
			BussUserOrder buo = new BussUserOrder();
			buo.setOrderNo(orderNo);
			buo = bussUserOrderMapper.selectSingle(buo);
			if (buo != null) {
				buo.setOrderIsreward(1);
				buo.setRewardId(bur.getId());
				bussUserOrderMapper.updateByEntity(buo);

				// 3.更新资金账户
				handleUserRewardMoney(bur);

				try {
					messageService.addMessage(1, "2", "订单打赏通知", "尊敬的 " + buo.getLinkMan() + "，您打赏的 订单 " + orderNo
							+ " 已经成功，感谢您对我们洗车工服务的认可，我们会更加努力为您提供优质服务，谢谢！！", buo.getUserId().toString());
					// 给洗车工发送短信通知
					BussWasherInfo ws = new BussWasherInfo();
					ws.setId(buo.getWasherId());
					ws = washerInfoMapper.selectSingle(ws);
					if (ws != null) {
						// SmsUtils.sendOrdNotice(ws.getWasherMobile(),
						// ws.getWasherRealname(), buo.getOrderNo(),
						// DateCompareUtil.getDateToString(buo.getBespokeBeginTime())
						// + "-"
						// +
						// DateCompareUtil.getDateToString(buo.getBespokeEndTime()));

						messageService
								.addMessage(
										2, "2", "订单打赏通知", "尊敬的 " + ws.getWasherRealname() + "，您的 新订单 " + orderNo
												+ " 已被 " + buo.getLinkMan() + "打赏，请再接再厉，更加努力的为客户服务，谢谢！",
										ws.getId().toString());
					}
				} catch (Exception e) {
					LOGGER.error("订单支付-微信支付发送站内信息或者短信失败，订单号为 ： " + orderNo);
				}

				return true;
			}
		} else {
			return false;
		}

		return false;
	}

	// /**
	// * 余额支付打赏金额
	// */
	// public String createAccountRrewardOrder(Map<String, Object> map) {
	// BussUserOrder buo = new BussUserOrder();
	// buo.setId(Long.valueOf(map.get("id").toString()));
	// buo = bussUserOrderMapper.selectSingle(buo);
	// if (buo != null) {
	// // 1. 先创建一条打赏订单记录
	// long orderBalance = Long.valueOf(map.get("orderBalance").toString());
	// String orderNo = createReward(buo, orderBalance);
	// // 创建本地订单
	// if (!StringUtils.isEmpty(orderNo)) {
	// return orderNo;
	// } else {
	// return null;
	// }
	// }
	// return null;
	// }

	/**
	 * 订单打赏 - 余额支付
	 */
	public int payAccountRrewardOrder(Map<String, Object> map) throws ClientException {

		// 1.获取到订单信息，更新订单支付状态，变更用户资金明细，分配订单给洗车工
		BussUserOrder vo = new BussUserOrder();
		vo.setOrderNo(map.get("orderNo").toString());
		long userId = Long.valueOf(map.get("userId").toString());
		vo.setUserId(userId);

		// 验证支付密码是否正确
		BussUserInfo bi = new BussUserInfo();
		bi.setId(Integer.valueOf(map.get("userId").toString()));
		bi = userInfoMapper.selectSingle(bi);
		String userPaypwd = map.get("userPaypwd").toString();
		userPaypwd = PasswordEncoder.getPassword(userPaypwd);
		if (bi != null) {
			String payPassword = bi.getUserPaypwd();
			if (!StringUtils.isEmpty(payPassword)) {
				if (payPassword.equals(userPaypwd)) {
					vo = bussUserOrderMapper.selectSingle(vo);
					if (vo != null) {
						// 1. 先创建一条打赏订单记录
						long orderBalances = Long.valueOf(map.get("orderBalance").toString());
						String orderNo = createReward(vo, orderBalances);
						BussUserReward bur = new BussUserReward();
						bur.setOrderNo(orderNo);
						bur = bussUserRewardMapper.selectSingle(bur);
						if (bur != null) {
							// 获取用户账户，查询是否有足够的资金进行支付
							BussUserFundstatistics bcf = new BussUserFundstatistics();
							bcf.setObjectId(userId);
							bcf = userFundstatisticsMapper.selectSingle(bcf);

							// 这个是订单金额，也就是打赏金额
							long orderBalance = bur.getOrderBalance();

							if (bcf.getBalance() >= orderBalance) {
								// 账户余额中赠送金额
								long giveBalance = bcf.getGiveBalance();

								// 账户余额中充值金额
								long rechargebalance = bcf.getRechargeBalance();

								long regiveBalance = 0l;
								long rerechargebalance = 0l;

								if (orderBalance % 2 == 0) {
									if (rechargebalance - orderBalance * 0.5 >= 0) {
										if (giveBalance - orderBalance * 0.5 >= 0) {
											// 充值金额 和 赠送金额各个减订单金额一半
											regiveBalance = orderBalance / 2;
											rerechargebalance = orderBalance / 2;
										} else {
											regiveBalance = giveBalance;
											rerechargebalance = orderBalance - giveBalance;
										}
									} else {
										rerechargebalance = rechargebalance;
										regiveBalance = orderBalance - rechargebalance;
									}
								} else {
									if (rechargebalance - orderBalance > 0) {
										rerechargebalance = orderBalance;
										regiveBalance = 0;
									} else {
										rerechargebalance = rechargebalance;
										regiveBalance = orderBalance - rechargebalance;
									}
								}

								bur.setOrderStatus(2);
								bussUserRewardMapper.updateByEntity(bur);
								// 更新订单支付状态
								vo.setOrderIsreward(1);
								vo.setRewardId(bur.getId());
								bussUserOrderMapper.updateByEntity(vo);

								// 创建订单后，对于用户的账户资金进行修改
								handlepayAccountRrewardOrder(bur.getOrderBalance(), rerechargebalance, regiveBalance,
										Integer.valueOf(map.get("userId").toString()), bur.getId(), vo.getWasherId());
								try {
									messageService.addMessage(1, "2", "订单打赏通知",
											"尊敬的 " + vo.getLinkMan() + "，您打赏的 订单 " + orderNo
													+ " 已经成功，感谢您对我们洗车工服务的认可，我们会更加努力为您提供优质服务，谢谢！！",
											vo.getUserId().toString());
									// 给洗车工发送短信通知
									BussWasherInfo ws = new BussWasherInfo();
									ws.setId(vo.getWasherId());
									ws = washerInfoMapper.selectSingle(ws);
									if (ws != null) {
										// SmsUtils.sendOrdNotice(ws.getWasherMobile(),
										// ws.getWasherRealname(),
										// buo.getOrderNo(),
										// DateCompareUtil.getDateToString(buo.getBespokeBeginTime())
										// + "-"
										// +
										// DateCompareUtil.getDateToString(buo.getBespokeEndTime()));

										messageService.addMessage(2, "2", "订单打赏通知",
												"尊敬的 " + ws.getWasherRealname() + "，您的 新订单 " + orderNo + " 已被 "
														+ vo.getLinkMan() + "打赏，请再接再厉，更加努力的为客户服务，谢谢！",
												ws.getId().toString());
									}
								} catch (Exception e) {
									LOGGER.error("订单支付-微信支付发送站内信息或者短信失败，订单号为 ： " + orderNo);
								}

								return 0;
							} else {
								return 2;
							}
						} else {
							return 1;
						}
					} else {
						return 3;
					}
				} else {
					return 5;
				}
			} else {
				return 4;
			}

		} else {
			return 6;
		}
	}

	/**
	 * 对于余额支付后对账户资金变化情况
	 * 
	 * @param bo
	 * @param rechargebalance
	 * @param giveBalance
	 */
	public void handlepayAccountRrewardOrder(long orderBalance, long rechargebalance, long giveBanlance, int userId,
			int id, int wid) {

		// 2. 创建用户明细表
		createUserFunddetails(orderBalance, giveBanlance, userId, id, 31);

		// 3. 修改用户资金总表信息
		updateUserFundstatisticsReduce(orderBalance, userId, rechargebalance, giveBanlance);

		// 3. 创建一条明细记录（洗车工增加资金）
		createWasherFunddetails(orderBalance, wid, id, 2);
	}

	/**
	 * 对于洗车订单使微信支付
	 */
	public Map<String, Object> payWxOrder(Map<String, Object> map) throws ClientException {
		int payType = Integer.valueOf(map.get("payType").toString());
		String orderNo = map.get("orderNo").toString();
		if (payType == 1) { // 公众号支付
			// 创建本地订单
			if (!StringUtils.isEmpty(orderNo)) {
				BussUserOrder vo = new BussUserOrder();
				vo.setOrderNo(orderNo);
				vo = bussUserOrderMapper.selectSingle(vo);
				if (vo != null) {

					// 用户同意授权，获得的code
					String code = map.get("openid").toString();

					// 调用统一下单service
					WXOrderVO VO = new WXOrderVO();
					VO.setBody("凤凰洗车-共享洗车服务");
					VO.setOpenid(code);
					VO.setOrderNo(orderNo);
					VO.setNotityUrl(Constant.PUNOTIFY_URL);
					VO.setOrderBalance(vo.getOrderBalance().intValue());
					Map<String, Object> maps = payService.unifiedOrder(VO);

					if (maps != null) {
						// 修改订单支付单
						BussUserConsumorder buc = new BussUserConsumorder();
						buc.setOrderNo(orderNo);
						buc = bussUserConsumorderMapper.selectSingle(buc);
						if (buc != null) {
							buc.setServicesNo(maps.get("package").toString());
							bussUserConsumorderMapper.updateByEntity(buc);

							vo.setTradeType(payType);
							vo.setRechargeType(1);
							bussUserOrderMapper.updateByEntity(vo);
							return maps;
						}
					}
				} else {
					return null;
				}
			} else {
				return null;
			}
		} else if (payType == 2) {
			// APP 微信支付
			// 创建本地订单
			if (!StringUtils.isEmpty(orderNo)) {
				BussUserOrder vo = new BussUserOrder();
				vo.setOrderNo(orderNo);
				vo = bussUserOrderMapper.selectSingle(vo);
				if (vo != null) {
					// 调用统一下单service
					WXOrderVO VO = new WXOrderVO();
					VO.setBody("凤凰洗车-共享洗车服务");
					VO.setOrderNo(orderNo);
					VO.setNotityUrl(Constant.PUNOTIFY_URL);
					VO.setOrderBalance(vo.getOrderBalance().intValue());
					Map<String, Object> maps = payService.unifiedOrderForApp(VO);

					if (maps != null && maps.get("prepayid") != null) {
						// 修改订单支付单
						BussUserConsumorder buc = new BussUserConsumorder();
						buc.setOrderNo(orderNo);
						buc = bussUserConsumorderMapper.selectSingle(buc);
						if (buc != null) {
							buc.setServicesNo(maps.get("prepayid").toString());
							bussUserConsumorderMapper.updateByEntity(buc);
							vo.setTradeType(payType);
							vo.setRechargeType(1);
							bussUserOrderMapper.updateByEntity(vo);
							return maps;
						}
					}
				} else {
					return null;
				}
			}
			return null;
		} else {
			return null;
		}
		return null;
	}

	@Override
	public boolean modifyRefundOrder(String transaction_id, String orderBalance, String orderNo) {
		BussUserOrder bo = new BussUserOrder();
		bo.setOrderNo(orderNo);
		bo = bussUserOrderMapper.selectSingle(bo);
		if (bo != null) {
			bo.setExamineStatus(2); // 退款申请审核（系统管理员）（0-不用审核；1-等待审核；2-通过；3-不通过）
			bo.setOrderStatus(21); // 订单状态(1-未开始；2-开始服务；3-服务完成；10-订单取消；20-申请退款;21-完成退款；30-已结算)
			bo.setBespokeEndTime(DateCompareUtil.getNowDate());

			bussUserOrderMapper.updateByEntity(bo);
			
			BussWasherInfo ws = new BussWasherInfo();
			ws.setId(bo.getWasherId());
			ws = washerInfoMapper.selectSingle(ws);
			if (ws != null) {

				try {
					// SmsUtils.sendOrdNotice(ws.getWasherMobile(),
					// ws.getWasherRealname(), bo.getOrderNo(),
					// DateCompareUtil.getDateToString(bo.getBespokeBeginTime())
					// + "-"
					// +
					// DateCompareUtil.getDateToMils(bo.getBespokeEndTime()));

					messageService.addMessage(2, "2", "订单取消通知",
							"尊敬的 " + ws.getWasherRealname() + "，您的 新订单 " + bo.getOrderNo() + " 已经被用户取消服务！",
							ws.getId().toString());

					messageService.addMessage(1, "2", "订单取消通知", "尊敬的 " + bo.getLinkMan() + "，您的 订单 "
							+ bo.getOrderNo() + " 已经成功取消，感谢对我们的支持，请下次再来，谢谢！", bo.getUserId().toString());
				} catch (Exception e) {
					LOGGER.error("订单支付-微信支付发送站内信息或者短信失败，订单号为 ： " + bo.getOrderNo());
				}
			}
			return true;
		}
		return false;
	}

	@Override
	public int findOrderInfoBySpoke(Map<String, Object> map) throws ClientException {
		List<BussUserOrder> lis = bussUserOrderMapper.findOrderInfoBySpoke(map);
		if (lis != null && lis.size() > 0) {
			return lis.size();
		}
		return 0;
	}

	@Override
	public boolean washerProessRefunds(Map<String, Object> map) throws ClientException {

		// 订单状态(1-未开始；2-开始服务；3-服务完成；10-订单取消；20-申请退款;21-完成退款；30-已结算)
		try {
			BussUserOrder bo = new BussUserOrder();
			bo.setWasherId(Integer.valueOf(map.get("washerId").toString()));
			bo.setId(Long.valueOf(map.get("orderId").toString()));
			bo.setOrderStatus(20);
			bo = bussUserOrderMapper.selectSingle(bo);
			if (bo != null) {
				// 查看是那个支付方式 充值方式（1-微信支付；2-余额支付）
				int rechargeType = bo.getRechargeType();
				if (rechargeType == 1) {
					int payType = bo.getTradeType();
					if (payType == 1) {
						// 直接退款到微信账户
						WXOrderVO vo = new WXOrderVO();
						vo.setOrderBalance(bo.getOrderBalance().intValue());
						vo.setOrderNo(bo.getOrderNo());
						vo.setRefundBalance(bo.getOrderBalance().intValue());
						vo.setOutRefundNo(bo.getOrderNo() + "-1");
						vo.setNotityUrl(Constant.REFUND_URL);
						boolean rs = payService.refund(vo);
						if (rs) {
							bo.setOrderStatus(21);
							bussUserOrderMapper.updateByEntity(bo);
							return true;
						} else {
							return false;
						}
					} else if (payType == 2) {
						// 直接退款到微信账户
						WXOrderVO vo = new WXOrderVO();
						vo.setOrderBalance(bo.getOrderBalance().intValue());
						vo.setOrderNo(bo.getOrderNo());
						vo.setRefundBalance(bo.getOrderBalance().intValue());
						vo.setOutRefundNo(bo.getOrderNo() + "-1");
						vo.setNotityUrl(Constant.REFUND_URL);
						boolean rs = payService.refundForApp(vo);
						if (rs) {
							bo.setOrderStatus(21);
							bussUserOrderMapper.updateByEntity(bo);
							return true;
						} else {
							return false;
						}
					}

				} else if (rechargeType == 2) {
					// 需要退款到余额账户
					// 充值金额
					long rechargeBalance = bo.getRechargeBalance();
					long giveBalance = bo.getGiveBalance(); // 赠送金额
					long orderBalacne = bo.getOrderBalance();

					BussUserFundstatistics bcf = new BussUserFundstatistics();
					bcf.setObjectId(bo.getUserId());
					bcf = userFundstatisticsMapper.selectSingle(bcf);
					if (bcf != null) {
						long balance = bcf.getBalance();
						bcf.setBalance(balance + orderBalacne);
						bcf.setRechargeBalance(bcf.getRechargeBalance() + rechargeBalance);
						bcf.setGiveBalance(bcf.getGiveBalance() + giveBalance);
						bcf.setRewardBalance(bcf.getRewardBalance() - balance);
						userFundstatisticsMapper.updateByEntity(bcf);
					}

					bo.setOrderStatus(21);
					bussUserOrderMapper.updateByEntity(bo);
					
					BussWasherInfo ws = new BussWasherInfo();
					ws.setId(bo.getWasherId());
					ws = washerInfoMapper.selectSingle(ws);
					if (ws != null) {

						try {
							// SmsUtils.sendOrdNotice(ws.getWasherMobile(),
							// ws.getWasherRealname(), bo.getOrderNo(),
							// DateCompareUtil.getDateToString(bo.getBespokeBeginTime())
							// + "-"
							// +
							// DateCompareUtil.getDateToMils(bo.getBespokeEndTime()));

							messageService.addMessage(2, "2", "订单取消通知",
									"尊敬的 " + ws.getWasherRealname() + "，您的 新订单 " + bo.getOrderNo() + " 已经被用户取消服务！",
									ws.getId().toString());

							messageService.addMessage(1, "2", "订单取消通知", "尊敬的 " + bo.getLinkMan() + "，您的 订单 "
									+ bo.getOrderNo() + " 已经成功取消，感谢对我们的支持，请下次再来，谢谢！", bo.getUserId().toString());
						} catch (Exception e) {
							LOGGER.error("订单支付-微信支付发送站内信息或者短信失败，订单号为 ： " + bo.getOrderNo());
						}
					}
				}

				return true;
			} else {
				return false;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	@Override
	public boolean cancelOrder(Map<String, Object> map) throws ClientException {

		// 订单状态(1-未开始；2-开始服务；3-服务完成；10-订单取消；20-申请退款;21-完成退款；30-已结算)
		try {
			BussUserOrder bo = new BussUserOrder();
			bo.setId(Long.valueOf(map.get("id").toString()));
			bo = bussUserOrderMapper.selectSingle(bo);
			if (bo != null) {
				// 查看是那个支付方式 充值方式（1-微信支付；2-余额支付）
				int rechargeType = bo.getRechargeType();
				if (rechargeType == 1) {
					int payType = bo.getTradeType();
					if (payType == 1) {
						// 直接退款到微信账户
						WXOrderVO vo = new WXOrderVO();
						vo.setOrderBalance(bo.getOrderBalance().intValue());
						vo.setOrderNo(bo.getOrderNo());
						vo.setRefundBalance(bo.getOrderBalance().intValue());
						vo.setOutRefundNo(bo.getOrderNo() + "-1");
						vo.setNotityUrl(Constant.REFUND_URL);
						boolean rs = payService.refund(vo);
						if (rs) {
							bo.setOrderStatus(10);
							bussUserOrderMapper.updateByEntity(bo);
							return true;
						} else {
							return false;
						}
					} else if (payType == 2) {
						// 直接退款到微信账户
						WXOrderVO vo = new WXOrderVO();
						vo.setOrderBalance(bo.getOrderBalance().intValue());
						vo.setOrderNo(bo.getOrderNo());
						vo.setRefundBalance(bo.getOrderBalance().intValue());
						vo.setOutRefundNo(bo.getOrderNo() + "-1");
						vo.setNotityUrl(Constant.REFUND_URL);
						boolean rs = payService.refundForApp(vo);
						if (rs) {
							bo.setOrderStatus(10);
							bussUserOrderMapper.updateByEntity(bo);
							return true;
						} else {
							return false;
						}
					}

				} else if (rechargeType == 2) {
					// 需要退款到余额账户
					// 充值金额
					long rechargeBalance = bo.getRechargeBalance();
					long giveBalance = bo.getGiveBalance(); // 赠送金额
					long orderBalacne = bo.getOrderBalance();

					BussUserFundstatistics bcf = new BussUserFundstatistics();
					bcf.setObjectId(bo.getUserId());
					bcf = userFundstatisticsMapper.selectSingle(bcf);
					if (bcf != null) {
						long balance = bcf.getBalance();
						bcf.setBalance(balance + orderBalacne);
						bcf.setRechargeBalance(bcf.getRechargeBalance() + rechargeBalance);
						bcf.setGiveBalance(bcf.getGiveBalance() + giveBalance);
						bcf.setRewardBalance(bcf.getRewardBalance() - balance);
						userFundstatisticsMapper.updateByEntity(bcf);
					}

					bo.setOrderStatus(10);
					bussUserOrderMapper.updateByEntity(bo);
					BussWasherInfo ws = new BussWasherInfo();
					ws.setId(bo.getWasherId());
					ws = washerInfoMapper.selectSingle(ws);
					if (ws != null) {

						try {
							// SmsUtils.sendOrdNotice(ws.getWasherMobile(),
							// ws.getWasherRealname(), bo.getOrderNo(),
							// DateCompareUtil.getDateToString(bo.getBespokeBeginTime())
							// + "-"
							// +
							// DateCompareUtil.getDateToMils(bo.getBespokeEndTime()));

							messageService.addMessage(2, "2", "订单取消通知",
									"尊敬的 " + ws.getWasherRealname() + "，您的 新订单 " + bo.getOrderNo() + " 已经被用户取消服务！",
									ws.getId().toString());

							messageService.addMessage(1, "2", "订单取消通知", "尊敬的 " + bo.getLinkMan() + "，您的 订单 "
									+ bo.getOrderNo() + " 已经成功取消，感谢对我们的支持，请下次再来，谢谢！", bo.getUserId().toString());
						} catch (Exception e) {
							LOGGER.error("订单支付-微信支付发送站内信息或者短信失败，订单号为 ： " + bo.getOrderNo());
						}
					}
				}

				return true;
			} else {
				return false;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	@Override
	public BussUserOrder findOrderInfoByLogin(Map<String, Object> map) {
		BussUserOrder bussUserOrder = bussUserOrderMapper.findOrderInfoByLogin(map);
		if (bussUserOrder != null) {
			return bussUserOrder;
		}
		return null;
	}

}
